import { useEffect, useState } from 'react';
import { useAppStore } from '@/stores/appStore';
import { MainStage } from '@/components/ui/layout/MainStage';
import { Header } from '@/components/ui/layout/Header';
import { SidePanel } from '@/components/ui/layout/SidePanel';
import { TimelineController } from '@/components/ui/controls/TimelineController';
import { ParticleBackground } from '@/components/ui/ParticleBackground';
import { LoadingScreen } from '@/components/ui/LoadingScreen';
import { ErrorDisplay } from '@/components/ui/ErrorDisplay';
import { RecordAssetModal } from '@/components/ui/modals/RecordAssetModal';
import { usePerformanceMonitor } from '@/hooks/usePerformanceMonitor';
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts';
import { useDataLoader } from '@/hooks/useDataLoader';
import { useRecordAssetModal } from '@/hooks/useRecordAssetModal';

function App() {
  const { 
    loading, 
    error, 
    fullscreen, 
    sidebarOpen, 
    visualSettings,
    setLoading,
    setError 
  } = useAppStore();
  
  const [appReady, setAppReady] = useState(false);
  
  // Custom hooks for app functionality
  usePerformanceMonitor();
  useKeyboardShortcuts();
  useDataLoader();
  
  // RecordAsset弹窗管理
  const { modalState, closeModal, confirmModal } = useRecordAssetModal();
  
  // Initialize app
  useEffect(() => {
    const initializeApp = async () => {
      try {
        setLoading(true);
        
        // Simulate initialization process
        await new Promise(resolve => setTimeout(resolve, 1500));
        
        // Load initial data
        console.log('�� Initializing ZK Proof Visualization Demo...');
        
        // Set app as ready
        setAppReady(true);
        setLoading(false);
        
        console.log('✅ App initialization complete');
      } catch (err) {
        console.error('❌ App initialization failed:', err);
        setError(err instanceof Error ? err.message : 'Failed to initialize app');
        setLoading(false);
      }
    };
    
    initializeApp();
  }, [setLoading, setError]);
  
  // Handle fullscreen mode
  useEffect(() => {
    if (fullscreen) {
      document.documentElement.requestFullscreen?.();
    } else {
      document.exitFullscreen?.();
    }
  }, [fullscreen]);
  
  // Apply visual settings
  useEffect(() => {
    const root = document.documentElement;
    
    // Apply theme
    root.classList.toggle('dark', visualSettings.theme === 'dark');
    
    // Apply reduced motion
    if (visualSettings.reducedMotion) {
      root.style.setProperty('--animation-duration', '0.01ms');
    } else {
      root.style.removeProperty('--animation-duration');
    }
    
    // Apply high contrast
    root.classList.toggle('high-contrast', visualSettings.highContrast);
  }, [visualSettings]);
  
  // Show loading screen during initialization
  if (loading && !appReady) {
    return <LoadingScreen />;
  }
  
  // Show error if initialization failed
  if (error) {
    return <ErrorDisplay error={error} />;
  }
  
  return (
    <div className={`app-container ${fullscreen ? 'fullscreen' : ''}`}>
      {/* Background particles */}
      <ParticleBackground 
        particleCount={visualSettings.particleCount}
        animationQuality={visualSettings.animationQuality}
      />
      
      {/* Main layout */}
      <div className="app-layout">
        {/* Header - Fixed top */}
        {!fullscreen && <Header />}
        
        {/* Main content area - Flexible middle */}
        <div className="flex-1 flex relative">
          {/* Main stage */}
          <MainStage />
          
          {/* Side panel */}
          {sidebarOpen && <SidePanel />}
        </div>
        
        {/* Timeline controller - Fixed bottom */}
        {!fullscreen && <TimelineController />}
      </div>
      
      {/* RecordAsset参数输入弹窗 */}
      <RecordAssetModal
        isOpen={modalState.isOpen}
        onClose={closeModal}
        onConfirm={confirmModal}
        dataHash={modalState.dataHash}
        defaultDataDetails={modalState.defaultDataDetails}
      />
      
      {/* Global error boundary */}
      {error && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <ErrorDisplay error={error} />
        </div>
      )}
    </div>
  );
}

export default App;
